<script lang="ts" setup>
import { ref, inject, onMounted } from 'vue';
import HeaderDemo from '../components/HeaderDemo.vue';
import { ElMessage } from 'element-plus'
import CryptoJS from 'crypto-js'
import type { TabsPaneContext } from 'element-plus'
import ScriptCard from '../components/ScriptCard.vue';
import Message from '../views/Message.vue';
import { useRoute, useRouter } from 'vue-router';  // 确保引入 useRoute
import { useTokenStore } from '../stores/token'

const axios = inject('axios') // 注入 axios
const route = useRoute();
const router = useRouter(); // 初始化 router 对象
const uid = route.params.uid;  // 获取传递的 uid 参数
console.log('接收到的 uid:', uid);
const userStore = useTokenStore();
const token = ref(userStore.getToken());

// 用户数据
const user = ref({});
// 默认头像
const avatarUrl = ref('../../public/images/head.png'); // 初始头像URL  
const showEnlarged = ref(false); // 控制放大头像的显示与隐藏
const showModal = ref(false);  //控制模态框显示/隐藏
const nickname = ref('');  // 当前显示的信息
const newnickname = ref('');  // 临时存储用户输入的新信息
const newAvatar = ref(null);  // 存储上传的头像预览
const fileInput = ref(null);  // 引用隐藏的文件输入框
const errorMessage = ref('');
const label = ref('');
const newlabel = ref('');
const scriptCount = ref(0); // 定义剧本统计数量

// 更新 scriptCount 的函数，从子组件接收新的 scriptCount
const updateScriptCount = (count: number) => {
  scriptCount.value = count; // 更新 scriptCount 的值
  console.log('父组件接收到的 scriptCount:', count); // 记录日志，确保接收到了更新
};

const handleSubmit = () => {
  // 重置错误和成功消息  
  errorMessage.value = '';
  newnickname.value = '';
  newlabel.value = '';

  // 校验逻辑  
  if (!newnickname.value) {
    errorMessage.value = '输入框不能为空';
  } else if (newnickname.value.length > 20) {
    errorMessage.value = '最多只能输入20个字';
  } else {
    newnickname.value = newnickname.value;
  }

  if (!newlabel.value) {
    errorMessage.value = '输入框不能为空';
  } else if (newlabel.value.length > 200) {
    errorMessage.value = '最多只能输入200个字';
  } else {
    newlabel.value = newlabel.value;
  }
};

const activeName = ref('first');

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};

// 触发文件选择器
const triggerFileInput = () => {
  fileInput.value.click();
};

// 预览新头像
const previewAvatar = (event) => {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = () => {
      newAvatar.value = reader.result; // 将新头像的URL设置到 newAvatar
    };
    reader.readAsDataURL(file);
  }
};

// 确认修改头像
const confirmAvatarChange = () => {
  avatarUrl.value = newAvatar.value; // 将预览的头像替换为当前头像
  newAvatar.value = null; // 清空预览头像
};

// 取消修改头像
const cancelAvatarChange = () => {
  newAvatar.value = null; // 取消预览，恢复为原头像
};

// 更新信息的方法
const updateInfo = () => {
  nickname.value = newnickname.value; // 将新信息绑定到 info
  label.value = newlabel.value;
  avatarUrl.value = newAvatar.value;
  showModal.value = false; // 关闭模态框
};

// 获取登录的 Token
function getToken() {
  const encryptedToken = localStorage.getItem('token');
  if (encryptedToken) {
    const secretKey = 'your_secret_key';
    const bytes = CryptoJS.AES.decrypt(encryptedToken, secretKey);
    const decryptedToken = bytes.toString(CryptoJS.enc.Utf8);
    return decryptedToken;
  }
  return null;
}

// 获取用户信息
function initUser() {
  const Token = getToken();
  console.log("token:" + Token);
  if (Token != null) {
    console.log("开始初始化用户信息");
    axios({
      method: 'get',
      url: 'http://localhost:8080/user/getuser',
      headers: {
        Authorization: 'Bearer ' + Token
      }
    })
      .then(function (response) {
        console.log("code:" + response.data.code);
        if (response.data.code == '200') {
          console.log("用户信息获取成功：" + response.data.user.account);
          user.value = response.data.user;
          avatarUrl.value = 'http://localhost:8080/api/images/' + user.value.headlmg;
        }
      })
      .catch(function (error) {
        console.error(error);
        if (error.response?.status == 401) {
          token.value = '';
          userStore.setToken('');
          ElMessage({
            message: '请重新登录',
            type: 'success',
            plain: true
          });
        }
      });
  }
}

// 跳转到工作台页面
function goStaging() {
  router.push('/staging');
}

// 页面加载时调用初始化
onMounted(() => {
  initUser();
  console.log('页面加载完成');
});
</script>

<template>
  <div class="common-layout">
    <el-container>
      <!--导航栏-->
      <el-header>
        <HeaderDemo />
      </el-header>
      <!--个人内容-->
      <el-main>
        <div class="x">
          <div class="big-box">
            <div class="basic-box">
              <div>
                <span>
                  <img class="avatar" :src="avatarUrl" @click="showEnlarged = true" alt="头像">
                </span>
              </div>
              <!-- 放大显示的头像，默认隐藏 -->
              <div v-if="showEnlarged" class="enlarged-avatar-container">
                <img :src="avatarUrl" class="enlarged-avatar" alt="放大头像" />
                <!-- 点击图片或容器外部关闭放大效果 -->
                <button @click="showEnlarged = false" class="close-button">X</button>
              </div>
              <!--基本信息-->
              <div>
                <div class="name-box">
                  <h1 style="margin-top: 0px;">
                    <span v-if="nickname">{{ nickname }}</span>
                  </h1>
                  <div class="rz-box">
                    <span style="font-size: 26px;">{{ user.uname }}</span>
                    <img  src="../../public/images/rz.png" style="width:23px;" />
                    <!-- <span style="font-size: 13px;"></span> -->
                  </div>
                </div>
                <div class="data-box">
                  <div class="works-box">
                    <div class="works">作品数: {{ scriptCount }}</div>
                  </div>
                  <!-- <div class="id-box">
                  <div>用户ID:</div>
                  <span>42189624</span>
                </div> -->

                </div>
                <p class="id-box">
                  <span class="ID">账号ID: {{ user.account }}</span>
                  <span class="ageip">{{ user.email }}</span>
                  <span class="ageip">{{user.rolename}}</span>
                </p>
                <div class="sign-box">
                  <span class="sign">
                    <span v-if="label">{{ label }}</span>
                  </span>

                </div>

                <!-- <el-button round class="editorial-box" @click="showModal = true">编辑资料</el-button> -->
                <div class="btn-box">
                  <el-button type="primary" plain class="workbench-button" @click="goStaging">
                    <img src="../../public/images/工作台.jpg" alt="" style="width: 60px;border-radius: 14px;">
                  </el-button>
                  <p>工作台</p>
                </div>
                <!-- <Message /> -->

                <!-- 模态框，使用 v-if 控制显示/隐藏 -->
                <div v-if="showModal" class="modal">
                  <div class="modal-content">
                    <h3>编辑资料</h3>
                    <img :src="newAvatar" alt="" @click="triggerFileInput" class="avatar-image" />
                    <input type="file" ref="fileInput" @change="previewAvatar" accept="image/*" style="display: none" />
                    <!-- 绑定表单中的输入框 -->
                    <div>
                      <span>昵称</span>
                      <!-- <input v-model="newnickname" placeholder="请输入新名称" class="modify_box" /> -->
                      <el-input v-model="newnickname" placeholder="请输入新名称" class="modify_box" clearable />
                      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
                    </div>
                    <div>
                      <span>个签</span>
                      <!-- <input v-model="newlabel" placeholder="请输入新名称" class="modify_box" /> -->
                      <el-input v-model="newlabel" placeholder="请输入个签内容" class="modify_box" clearable />
                      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
                    </div>

                    <!-- 确定和取消按钮 -->

                    <div class="options_box">
                      <el-button @click="showModal = false" type="info">取消</el-button>
                      <el-button @click="updateInfo" color="#626aef" :dark="isDark" plain>确定</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!--钱包-->
            <div class="wallet-box">
              <div class="my-wallet-box">
                <img src="../../public/images/wallet.png"
                  style="width: 70px;height: 70px;margin-left: 10px;margin-top: 10px;">
                <p class="my-wallet">我的钱包</p>
              </div>
              <div class="yue-box">
                <p style="margin-left: 20px;">余额：
                  <span style="font-size: 20px;">100.00元</span>
                </p>
                <div class="xz">
                  <p style="margin-left: 20px;"><span>提现</span></p>
                  <p style="margin-left: 20px;"><span>充值</span></p>
                  <p style="margin-left: 20px;"><span>历史记录</span></p>
                </div>
              </div>
            </div>
          </div>

          <el-tabs type="border-card" class="demo-tabs"
            style="width: 100%;min-height: 800px;;height: auto;margin-top: 30px;z-index: 100;">
            <el-tab-pane>
              <template #label>
                <span class="custom-tabs-label">
                  <!-- <el-icon><calendar /></el-icon> -->
                  <span>我的作品</span>
                </span>
              </template>
              <ScriptCard v-if="uid" :uid="uid" @update-script-count="updateScriptCount" />
            </el-tab-pane>

          </el-tabs>
        </div>

      </el-main>
    </el-container>
  </div>
</template>

<style scoped>
.common-layout {
  background-image: url('../../public/images/bg02.jpg');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}

.workbench-button {
  width: 60px;
  height: 60px;
  margin-top: 1px;
  /* 你可以根据实际需求调整按钮的高度 */
  background-image: url('@/img/工作台.jpg');
  border-radius: 15px;
  background-size: cover;
  /* 使背景图片覆盖整个按钮 */
  /* background-position: center; */
  /* 图片居中显示 */
  background-repeat: no-repeat;
  /* 不重复显示图片 */
  border: none;
  /* 可以取消按钮默认的边框 */
}

.big-box {
  display: flex;
}

.basic-box {
  width: 85%;
  height: 200px;
  background-color: rgb(235, 230, 230, 0.6);
  margin-top: 40px;
  border-radius: 15px;
  display: flex;
}

.wallet-box {
  width: 15%;
  height: 200px;
  background-color: rgb(235, 230, 230, 0.6);
  margin-top: 40px;
  margin-left: 20px;
  border-radius: 15px;
  /* display: flex; */
}

.my-wallet-box {
  width: 205px;
  height: 90px;
  /* background-color: red; */
  display: flex;
  margin-top: 10px;

}

.my-wallet {
  font-size: 20px;
  margin-left: 10px;
  margin-top: 32px;
}

.yue-box {
  width: 205px;
  height: 90px;
  /* background-color: rgb(160, 212, 231); */
  margin-top: -20px;
  /* display: flex; */
}

.xz {
  display: flex;
  font-size: 13px;
}

.avatar {
  width: 130px;
  height: 130px;
  border-radius: 50%;
  margin: 30px;
  cursor: pointer;
  /* 鼠标悬停时显示手形图标，表示可点击 */
}

.enlarged-avatar-container {
  position: fixed;
  /* 固定定位，使放大头像覆盖整个页面 */
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
  background-color: rgba(0, 0, 0, 0.5);
  /* 半透明背景 */
  z-index: 1000;
  /* 确保覆盖在其他内容之上 */
}

.enlarged-avatar {
  width: 30%;
  /* 放大后的头像大小，可以根据需要调整 */
  height: auto;
  border-radius: 0px;
  /* 可选，给头像添加圆角 */
}

.close-button {
  position: absolute;
  /* 绝对定位，确保关闭按钮不会干扰头像显示 */
  top: 10px;
  right: 10px;
  padding: 5px 10px;
  background-color: rgb(180, 179, 179);
  border: none;
  cursor: pointer;
  border-radius: 5px;
}

.name-box {
  width: 400px;
  height: 30px;
  margin-top: 50px;
  /* background-color: red; */
  /* position: relative; */
  display: flex;
}

.rz-box {
  width: 150px;
  height: 30px;
  /* background-color: green; */
}

.data-box {
  width: 400px;
  height: 30px;
  /* background-color: rgb(136, 219, 249); */
  margin-top: 10px;
  display: flex;
}

.works-box {
  width: 100px;
  height: 30px;
  cursor: pointer;
  align-items: center;
  display: flex;
}

.works {
  margin-right: 10px;
  font-size: 17px;
  line-height: 22px;
}

.id-box {
  width: 400px;
  height: 20px;
  align-items: center;
  margin-top: 12px;
  display: flex;
  /* background-color: green; */
}

.ID {
  margin-right: 10px;
  font-size: 17px;
  line-height: 22px;
}

.ageip {
  height: 20px;
  border-radius: 4px;
  align-items: center;
  margin-right: 6px;
  margin-left: 10px;
  padding: 0 8px;
  font-size: 12px;
  line-height: 20px;
  display: flex;
  background-color: rgb(145, 199, 241, 0.5);
}

.sign-box {
  width: 1000px;
  height: 20px;
  margin-top: 4px;
  display: flex;
  position: relative;
}

.sign {
  font-size: 12px;
  font-weight: bold;
}

.classify-box {
  width: 100%;
  height: 600px;
  background-color: rgb(235, 232, 232, 0.6);
  border-radius: 10px;
  margin-top: 20px;
  display: flex;
}

.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.el-menu-popper-demo {
  margin-top: 10px;
  margin-left: 20px;
  width: 50%;
}

.editorial-box {
  /* width: 100px;
    height: 45px; */
  /* border-radius: 10%; */
  float: right;
  margin-right: 100px;
  margin-top: -100px;
  background-color: rgb(235, 232, 232, 0.9);
}

.btn-box {
  float: right;
  margin-top: -130px;
}
.btn-box p {
  margin-left: 6px;
  color: rgb(227, 224, 224);
  font-weight: 700;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 200;
}

.modal-content {
  width: 450px;
  height: 500px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  flex-direction: column;
  /* 设置为列方向 */
  /* display: flex;   */
  /* justify-content: center;   */
  /* align-items: center; */
}

.avatar-image {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #ccc;
  display: flex;
  margin-left: 30%;
}

.modify_box {
  width: 350px;
  height: 40px;
  margin-top: 20px;
  margin-left: 10px;
  /* border: #c7c5c5 1px solid; */
}

.error-message {
  color: red;
  font-size: 0.9em;
  margin-top: 5px;
}

.options_box {
  margin-top: 50px;
  float: right;
}

.demo-tabs>.el-tabs__content {
  width: 1000px;
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.demo-tabs>.el-tabs__content {
  width: 100%;
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.demo-tabs .custom-tabs-label .el-icon {
  vertical-align: middle;
}

.demo-tabs .custom-tabs-label span {
  vertical-align: middle;
  margin-left: 4px;
}
</style>